package netWorkPrograming.tcp.tcp06;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author yangwenqi
 * @decs TODO
 * @date 2025/5/27
 */
public class WriterThread implements Runnable {
    private Socket socket;
    public WriterThread(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        /*
        当在写线程里输入 “exit” 并且退出 run() 方法时，你的写线程会因为 try-with-resources
        而关闭它内部的 PrintWriter，而关闭 PrintWriter 会顺带关闭底层的 socket 输出流，最终会把整个 Socket
        标记为已关闭。此时，正在另一个线程里阻塞在
         */
        PrintWriter out = null;
        try(Scanner in = new Scanner(System.in);
        ) {
            out = new PrintWriter(socket.getOutputStream(), true);
            while (true) {
                System.out.println("请输入：");
                String str=in.nextLine();
                if(str.equals("exit")){
                    System.out.println("退出");
                    break;
                }
                out.println(str);
            }
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (out != null) {
                out.close();
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
